package com.echo.yixiaowu.feature.components

import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.UiComposable
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp

@Composable
fun ImageGridLayout(
    modifier: Modifier = Modifier,
    contentPadding: Dp = 0.dp,
    rowSpacing: Dp = 8.dp,
    columnSpacing: Dp = 8.dp,
    content: @Composable @UiComposable (() -> Unit)
) {
    Layout(modifier = modifier, content = content) { measurable, constraints ->
        when (measurable.size) {
            1 -> {
                val placeable = measurable.first().measure(constraints)
                layout(placeable.width, placeable.height) {
                    placeable.placeRelative(0, 0)
                }
            }

            else -> {
                val paddingPx = contentPadding.toPx().toInt()
                val rowSpacePx = rowSpacing.toPx().toInt()
                val colSpacePx = columnSpacing.toPx().toInt()
                val fixedCount = when (measurable.size) {
                    2, 4 -> 2
                    else -> 3
                }
                val rowCount = (measurable.take(9).size + fixedCount - 1) / fixedCount
                val itemWidth =
                    (constraints.maxWidth - 2 * paddingPx - (fixedCount - 1) * colSpacePx) / fixedCount
                val itemConstraints = constraints.copy(minWidth = itemWidth, maxWidth = itemWidth)
                val placeable = measurable.take(9).map { it.measure(itemConstraints) }
                val itemHeight = placeable.firstOrNull()?.height ?: 0
                val totalHeight =
                    rowCount * itemHeight + (rowCount - 1) * rowSpacePx + 2 * paddingPx
                layout(constraints.maxWidth, totalHeight) {
                    placeable.forEachIndexed { index, placeable ->
                        val row = index / fixedCount
                        val col = index % fixedCount

                        val x = paddingPx + col * (itemWidth + colSpacePx)
                        val y = paddingPx + row * (itemHeight + rowSpacePx)

                        placeable.placeRelative(x, y)
                    }
                }
            }
        }
    }
}